package engine;

import java.awt.Point;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import movables.Snake;

public class Board implements Observer{

	private ArrayList<Cell> cells = new ArrayList<Cell>();
	private ArrayList<Snake> snakes = new ArrayList<Snake>();
	private int squareSize;
	private boolean randomComponents;


	public Board(int squareSize, int numberOfWalls,int numberOfFood,int numberOfBoost, boolean randomComponents){
		this.squareSize = squareSize;
		this.randomComponents = randomComponents;

		for (int y = 0; y < squareSize; y++)
			for (int x = 0; x < squareSize; x++){
				cells.add(new Cell(new Point(x, y)));
				cells.get(cells.size()-1).setCelltype(CellType.FLOOR);
			}

		for(int i=0; i<numberOfWalls; i++){
			int auxRand = (int)(Math.random()*cells.size());
			while (cells.get(auxRand).getPos().x == 0 || cells.get(auxRand).getPos().x == squareSize-1
					|| cells.get(auxRand).getPos().y == 0 || cells.get(auxRand).getPos().y == squareSize-1)
				auxRand = (int)(Math.random()*cells.size());
			cells.get(auxRand).setCelltype(CellType.WALL);
		}


		for(int i=0; i<numberOfFood; i++){
			int rand = (int)(Math.random()*cells.size());
			if(!cells.get(rand).getCelltype().equals(CellType.WALL))
				cells.get(rand).setCelltype(CellType.FOOD);
		}

		for (int i=0; i<numberOfBoost; i++)
			cells.get((int)(Math.random()*cells.size())).setCelltype(CellType.JUMP);

	}


	@Override
	public void update(Observable arg0, Object arg1) {
		if(randomComponents){
			if ((int)(Math.random()*30) == 1){
				int rand = (int)(Math.random()*cells.size());
				boolean done = false;
				while (!done){
					if (cells.get(rand).getCelltype().equals(CellType.FLOOR)){
						cells.get(rand).setCelltype(CellType.FOOD);
						done = true;
					}
				}	
			}
		}

	}

	public void addSnake(Snake snake) {
		snake.addObserver(this);
		snakes.add(snake);
	}

	public int getSquareSize(){
		return squareSize;
	}


	public ArrayList<Cell> getCells() {
		return cells;
	}

	public ArrayList<Snake> getSnakes() {
		return snakes;
	}

	public Cell getCell(int x, int y){
		return cells.get(x + y * squareSize);
	}
}
